import {
  ApiRootUrl,
  apiList
} from '../../../config/index.js'
import Dialog from '../../../@vant/weapp/dialog/dialog';
import {
  IMG_PATH
} from '../../../config/index.js'
import {
  request,formatDateTime,formatStringTime
} from "../../../utils/util.js"
import Toast from '../../../@vant/weapp/toast/toast';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IMG_PATH: IMG_PATH,
    birthday: '',
    currentDate: new Date().getTime(),
    // lizhiminDate: new Date(2010, 1, 1).getTime(),
    // lizhimaxDate: new Date(2030,1.1).getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}`;
      } else if (type === 'month') {
        return `${value}`;
      }
      return value;
    },
    lizhiTimeShow: false,
    isRange:false,
    lizhiTime:'请选择时间',
    zhusuShowColumns: ['已入宿', '未入宿'],
    zhusuShow: false,
    tongzhiShow: false,
    allpendingchecked: false,
    allchecked: false,
    tongzhimessage: '',
    height: 0,
    pageSize: 20,
    pageNumber: 1,
    total: 0,
    sourceCode:"",
    dangerId:"",
    isLoad:false,
    determineList: [],
    pendingList: [],
    passList: [],
    minDate: new Date(2000, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    sourceShow: false,
    dangerShow: false,
    timeshow: false,
    statusBarHeight: '',
    active: 0,
    searchValue: '',
    sourceName: '劳务公司',
    iszhusu: '是否住宿',
    time: '选择时间',
    danger: '备案登记',
    leaveTimeStart:"",
    leaveTimeEnd:"",
    sourceShowColumns: [],
    dangerShowColumns: [
      {
        id: '',
        text: '全部'
      },{
        id: '0',
        text: '未提交'
      }, {
        id: '1',
        text: '已提交'
      }, {
        id: '2',
        text: '备案中'
      }, {
        id: '3',
        text: '已备案'
      }],
    tabList: [{
      title: '已离职',
    }, {
      title: '未离职',
    }],
  },

  companyClick() {
    this.setData({
      sourceShow: true
    })
  },
  dangerShowClose() {
    this.setData({
      dangerShow: false
    })
  },
  zhusuShowClose() {
    this.setData({
      zhusuShow: false
    })
  },
  birthdadInput(event) {
    let time = this.formatDate(event.detail);
    let leaveTime = this.formatDate1(event.detail)
    console.log(time,leaveTime);
    this.setData({
      birthday: time,
    });
  },
  lizhiTimeClose() {
    this.setData({
      lizhiTimeShow: false
    })
  },
  familybirthdayConfirm(event) {
    
    let birthday = this.data.birthday;
    console.log(birthday);
    this.setData({
      lizhiTime: birthday,
      leaveTime:this.data.birthday,
      lizhiTimeShow: false,
      tongzhiShow: true
    })
  },
  zhusuClick() {
    this.setData({
      zhusuShow: true
    })
  },
  dangerClick() {
    this.setData({
      dangerShow: true
    })
  },
  sourceShowClose() {
    this.setData({
      sourceShow: false
    })
  },
  zhusuShowConfirm(event) {
    console.log(event.detail.value)
    this.setData({
      iszhusu: event.detail,
      zhusuShow: false
    })
  },
  dangerShowConfirm(event) {
    this.setData({
      danger: event.detail.value.text,
      dangerId:event.detail.value.id,
      dangerShow: false
    },()=>{
      if(this.data.active == 0){
        this.getLeaveJob();
      }
      if(this.data.active == 1){
        this.getOnJob()
      }
    })
  },
  getLeaveJobPage(){
    let params = {
      labourCode: this.data.sourceCode,
      // labourCode:"002",
      name: this.data.searchValue,
      phone: "",
      leaveTimeStart:this.data.leaveTimeStart,
      leaveTimeEnd:this.data.leaveTimeEnd,
      surveyStatus: this.data.dangerId== ""?"":Number(this.data.dangerId),
      pageNumber:this.data.pageNumber + 1,
      pageSize:20,
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.leaveJob, params).then((res) => {
     console.log("请求结果=====>",res)
     this.setData({
      pendingList:this.data.pendingList.concat(res.data.list),
      total:res.data.total,
      pageNumber:this.data.pageNumber + 1,
      isLoad:false
     })    
      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  getOnJobPage(){
    let params = {
      labourCode: this.data.sourceCode,
      // labourCode:"002",
      name: this.data.searchValue,
      phone: "",
      jobStatus:4,
      dormStatus:null,
      surveyStatus:this.data.dangerId== ""?"":Number(this.data.dangerId),
      pageNumber:this.data.pageNumber+1,
      pageSize:20,
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.onJob, params).then((res) => {
     console.log("请求结果=====>",res)
      this.setData({
        total:res.data.total,
        pageNumber:this.data.pageNumber + 1,
        determineList:this.data.determineList.concat(res.data.list),
        isLoad:false
      }) 
      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  loadMore(e){
    if(this.data.active == 0){
      if(this.data.pendingList.length < this.data.total){
        this.setData({
          isLoad:true
        })
        this.getLeaveJobPage()
      }
    }
    if(this.data.active == 1){
      if(this.data.determineList.length < this.data.total){
        this.setData({
          isLoad:true
        })
        this.getOnJobPage()
      }
      
    }
  },
  timeClick() {
    this.myComponent.showPicker()
    this.setData({
      timeshow: true
    })
  },
  sourceShowConfirm(event) {
    let text = event.detail.value.text;
    if(text == "全部"){
      text = "劳务公司"
    }
    this.setData({
      sourceName: text,
      sourceCode:event.detail.value.id,
      sourceShow: false
    },()=>{
      if(this.data.active == 0){
        this.getLeaveJob();
      }
      if(this.data.active == 1){
        this.getOnJob()
      }
    })
  },
  tabClick(event) {
    this.setData({
      active: event.detail.index,
      pageNumber:1
    },()=>{
      console.log("tabClick==>",Number(event.detail.index))
      if(Number(event.detail.index) == 0){
        this.getLeaveJob()
      }
      if(Number(event.detail.index) == 1){
        this.getOnJob()
      }
    })

  },
  dengjiClick(e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      tongzhiShow: true,
      registerId:id
    })
  },
  backClick(event) {
    console.log(event);
    wx.navigateBack();
    // Dialog.confirm({
    //   title: '返回',
    //   message: '请确认是否返回？',
    // }).then(() => {
    //   wx.navigateBack();
    // }).catch(() => {
    //   console.log('取消')
    // });
  },
  lizhiTimeClick() {
    this.setData({
      lizhiTimeShow: true,
    })
  },
  formatDate(date) {
    var date = new Date(date);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    return YY + MM + DD;
  },
  formatDate1(date) {
    var date = new Date(date);
    var YY = date.getFullYear() + '';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    return YY + MM + DD;
  },
  formateTime(time){
    let arr = time.split("-")
    return arr[0]+arr[1]+arr[2]+""
  },
  selectStart(e){
    let time = this.formateTime(e.detail)
    console.log("开始时间",e)
    this.setData({
      time: `${e.detail} - ${this.data.leaveTimeEnd}`,
      leaveTimeStart:time
    })
  },
  selectEnd(e){
    let time = this.formateTime(e.detail)
    console.log("结束时间",e)
    this.setData({
      time: `${this.data.leaveTimeStart} - ${e.detail}`,
      leaveTimeEnd:time
    })
  },
  timeConfirm(event) {
    // const [start, end] = event.detail;
    let beginTime = this.data.leaveTimeStart
    let endTime = this.data.leaveTimeEnd
    let time = beginTime+"-"+endTime
    if(!this.data.isRange){
      beginTime = "";
      endTime = "";
      time="选择时间"
    }
    this.setData({
      timeshow: false,
      leaveTimeStart:beginTime,
      leaveTimeEnd:endTime,
      time:time,
      isRange:false
    },()=>{
      if(Number(this.data.active) == 0){
        this.getLeaveJob()
      }
      if(Number(this.data.active) == 1){
        this.getOnJob()
      }
    });
    this.myComponent.hidePicker()
  },
  refendClick(event) {
    console.log(event);
    this.setData({
      tongzhiShow: true
    })
  },
  refendpendingClick(event) {
    console.log(event);
  },
  pendingChange(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    this.setData({
      determineList: dataList
    })
    if (event.detail) {
      this.setData({
        allpendingchecked: true
      })
    } else {
      let list = dataList.map(value => value['checked']);
      if (list.includes(true)) {
        this.setData({
          allpendingchecked: true
        })
      } else {
        this.setData({
          allpendingchecked: false
        })
      }

    }
  },
  pendingDetailsClick(event) {
    console.log(event);
    wx.navigateTo({
      url: `../detail/detail?id=${event.target.dataset.id}&type=${event.target.dataset.type}`
    })
  },
  refendpendingClick(event) {
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${event.target.dataset.id}`
    })
  },
  passChange(event) {
    console.log(event);
    let id = event.target.dataset.id;
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    this.setData({
      passList: dataList
    })
  },
  timeClose() {
    this.myComponent.hidePicker()
    this.setData({
      timeshow: false,
      isRange:false
    });
  },
  defalut(){
    //触发简历初始化，去除默认选择项
    const child = this.selectComponent('#Calendar');
    const child1 = this.selectComponent('#Calendar1');
    child.resetToday()
    child1.resetToday()
  },
  timeAll(){
    this.defalut()
    this.setData({
      timeshow: false,
      leaveTimeStart:"",
      leaveTimeEnd:"",
      time:"选择时间"
    },()=>{
      this.getLeaveJob();
    });
  },
  pendingallChange(event) {
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allpendingchecked: event.detail,
      determineList: dataList
    })
  },
  passallChange(event) {
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allchecked: event.detail,
      passList: dataList
    })
  },
  tongzhiClose() {
    this.setData({
      tongzhiShow: false,
      tongzhimessage: '',
    })
  },
  getRangeTime(e){
    let beginTime = formatDateTime(e.detail.begin);
    let endTime =formatDateTime(e.detail.end);
    console.log(beginTime,endTime)
    this.setData({
      leaveTimeStart:formatStringTime(beginTime),
      leaveTimeEnd:formatStringTime(endTime),
      isRange:true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let query = wx.createSelectorQuery();
    console.log("app.globalData.companyList",app.globalData.companyList)
    query.select('.content').boundingClientRect(rect => {
      let height = rect.height;
      this.setData({
        statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
        height: wx.getSystemInfoSync().windowHeight - height,
        sourceShowColumns:app.globalData.companyList||[],
      })
    }).exec();
    this.myComponent = this.selectComponent('#timeRangeComponent')
    this.getLeaveJob()
    // this.setData({
    //   sourceName: app.globalData.companyList[0].text,
    //   sourceCode:app.globalData.companyList[0].id
    // },()=>{
      
    // })
  },
  getLeaveJob() {
    let params = {
      labourCode: this.data.sourceCode,
      // labourCode:"002",
      name: this.data.searchValue,
      phone: "",
      leaveTimeStart:this.data.leaveTimeStart,
      leaveTimeEnd:this.data.leaveTimeEnd,
      surveyStatus: this.data.dangerId== ""?"":Number(this.data.dangerId),
      pageNumber:1,
      pageSize:20,
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.leaveJob, params).then((res) => {
     console.log("请求结果=====>",res)
     this.setData({
      pendingList:res.data.list,
      total:res.data.total
     })    
      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  getOnJob() {
    let params = {
      labourCode: this.data.sourceCode,
      // labourCode:"002",
      name: this.data.searchValue,
      phone: "",
      jobStatus:4,
      dormStatus:null,
      surveyStatus:this.data.dangerId== ""?"":Number(this.data.dangerId),
      pageNumber:1,
      pageSize:20,
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.onJob, params).then((res) => {
     console.log("请求结果=====>",res)
      this.setData({
        total:res.data.total,
        determineList:res.data.list
      })
     
      
      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  getSearchValue(e) {
    let value = e.detail;
    this.setData({
      searchValue: value
    }, () => {
      if(Number(this.data.active) == 0){
        this.getLeaveJob()
      }
      if(Number(this.data.active) == 1){
        this.getOnJob()
      }
    })
  },
  leaveJobeRegister(id,time){
    Toast.loading({
      message: '登记中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    this.setData({
      tongzhiShow:false,
    })
    let params ={
      idList:[id],
      leaveTime:time,
    }
    request(apiList.leaveJobeRegister,params).then(res => {
      Toast.clear();
      this.getOnJob()
    }).catch(err =>{
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
      this.setData({
        tongzhiShow:false,
      })
    })
  },
  sendClick(){
    if(this.data.lizhiTime == "请选择时间"){
      wx.showToast({
        icon:"none",
        title: '离职时间不能为空',
      })
      return
    }
    let time = this.formatTime(this.data.lizhiTime)
    this.leaveJobeRegister(this.data.registerId,time)
  },
  formatTime(time){
    return time.split("-")[0]+time.split("-")[1]+time.split("-")[2]
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})